<template>
  <div class="wrapper" ref="wrapper">
    <slot></slot>
  </div>
</template>

<script>
import BScroll from 'better-scroll';
import {reactive, getCurrentInstance, onMounted, toRefs} from "vue";

export default {
  name: "Scroller",
  props: {
    handleToScroll: {
      type: Function,
      default: function () {
      }
    },
    handleToTouchEnd: {
      type: Function,
      default: function () {
      }
    },
    handleToPullingDown: {
      type: Function,
      default: function () {
      }
    },
    handleToPullingUp: {
      type: Function,
      default: function () {
      }
    }
  },
  setup() {
    const state = reactive({});
    let {proxy} = getCurrentInstance();//暴露实例==>this
    onMounted(() => {
      proxy.$nextTick(() => {//$nextTick数据加载完毕后再开始渲染组件
        const scroll = new BScroll(proxy.$refs.wrapper, {//第一个参数是数据容器位置，第二个参数是配置设置Options
          tap: true,
          probeType: 1,
          observeDOM: true,//解决刷新后better-scroll失效
          scrollY: true,
          pullDownRefresh: {
            threshold: 100,//触发pullingDown事件的位置
            // stop: 0 //下拉回弹后停留的位置
          },
          /*pullUpLoad: {
            threshold: -50 // 当上拉距离超过30px时触发 pullingUp 事件
          }*/
        });
        scroll.on('pullingDown', (pos) => {
          proxy.handleToPullingDown(pos);
          scroll.finishPullDown();//每次下拉结束后，需要执行这个操作
          scroll.refresh();//当滚动区域的dom结构有变化时，需要执行这个操作
        })
        scroll.on('scroll', (pos) => {
          proxy.handleToScroll(pos);
        })
        /*scroll.on("pullingUp", (pos) => {
          this.handleToPullingUp(pos);
          scroll.finishPullUp();
          scroll.refresh();
        })*/
        scroll.on('touchEnd', (pos) => {
          proxy.handleToTouchEnd(pos);
        })
        proxy.scroll = scroll;
      })
    })

    return {
      state, proxy, ...toRefs(state)
    }
  },
  methods: {
    toScrollTop(y) {
      this.scroll.scrollTo(0, y);

    }
  }
}
</script>

<style scoped>
.wrapper {
  height: 100%;
}
</style>
